package com.warm.pump.executor;



import com.warm.pump.frame.util.RRException;
import com.warm.pump.frame.util.ScheduleStatus;
import com.warm.pump.module.skd.bean.po.gen.ScheduleJob;
import org.quartz.*;

import java.util.Date;

/**
 * 定时任务工具类(任务集)
 * Created by guozj on 2018/1/10
 */
public class TaskQuartzUtils {
    private final static String JOB_NAME = "GROUP_";

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long groupId) {
        return TriggerKey.triggerKey(JOB_NAME + groupId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long groupId) {
        return JobKey.jobKey(JOB_NAME + groupId);
    }

    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long groupId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(groupId));
        } catch (SchedulerException e) {
            throw new RRException("获取定时任务CronTrigger出现异常", e);
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJob job) {
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(TaskQuartzJob.class).withIdentity(getJobKey(job.getId())).build();

            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(job.getId())).withSchedule(scheduleBuilder).build();

            // 放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put("JOB_PARAM_KEY_GROUP", job);

            scheduler.scheduleJob(jobDetail, trigger);

            // 暂停任务
            if (job.getStatus() == ScheduleStatus.PAUSE.getValue()) {
                pauseJob(scheduler, job.getId());
            }
        } catch (SchedulerException e) {
            throw new RRException("创建定时任务失败", e);
        }
    }

    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJob job) {
        try {
            TriggerKey triggerKey = getTriggerKey(job.getId());

            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

            CronTrigger trigger = getCronTrigger(scheduler, job.getId());

            // 按新的cronExpression表达式重新构建trigger
            //.startAt(new Date()) 任务修改后防止其 立即执行一次
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).startAt(new Date()).build();

            // 参数
            trigger.getJobDataMap().put("JOB_PARAM_KEY_GROUP", job);
            scheduler.rescheduleJob(triggerKey, trigger);

            // 暂停任务
            if (job.getStatus() == ScheduleStatus.PAUSE.getValue()) {
                pauseJob(scheduler, job.getId());
            }

        } catch (SchedulerException e) {
            throw new RRException("更新定时任务失败", e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(Scheduler scheduler, ScheduleJob job) {
        try {
            // 参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put("JOB_PARAM_KEY_GROUP", job);

            scheduler.triggerJob(getJobKey(job.getId()), dataMap);
        } catch (SchedulerException e) {
            throw new RRException("立即执行定时任务失败", e);
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long id) {
        try {
            scheduler.pauseJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RRException("暂停定时任务失败", e);
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long id) {
        try {
            scheduler.resumeJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RRException("暂停定时任务失败", e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long id) {
        try {
            scheduler.deleteJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RRException("删除定时任务失败", e);
        }
    }
}
